package com.jiangjiang.eshop.common.util;

import org.apache.logging.log4j.util.Strings;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.sound.midi.Track;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.UUID;

/**
 * @ClassName FileUtils
 * @Description TODO
 * @Author jhw
 * @Date 2021/7/13 21:55
 * @Version 1.0
 **/
public class FileUtils {

    /**
     * 根据相对路径获取一个绝对路径
     * @param relativePath 相对路径
     * @return 绝对路径
     */
    public static String getPathByRelative(String relativePath)throws  Exception{
        File appBaseDir = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!appBaseDir.exists()){
            appBaseDir = new File("");
        }
        File targetFile = new File(appBaseDir.getAbsolutePath(),relativePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        return targetFile.getAbsolutePath();
    }


    /**
     * 上传一个文件
     * @param file 需要上传的文件
     * @param uploadPath 上传的路径
     * @return
     */
    public static String uploadFile(MultipartFile file,String uploadPath) throws Exception{
        if(Strings.isEmpty(file.getOriginalFilename())){
            return null;
        }

        File uploadDir = new File(uploadPath);
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        String pathSeparator = System.getProperties().getProperty("file.separator");
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
        String targetFilePath = uploadPath + pathSeparator + fileName;
        File targetFile = new File(targetFilePath);
        file.transferTo(targetFile);
        return targetFile.getAbsolutePath();
    }

    /**
     * 删除文件
     * @param filePath 文件路径
     * @return 文件
     * @throws Exception
     */
    public static Boolean deleteFile(String filePath) throws Exception {
        File file = new File(filePath);
        return file.delete();
    }


    public static void main(String[] args) throws FileNotFoundException {
        File appBaseDir = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!appBaseDir.exists()){
            appBaseDir = new File("");
        }
        File targetFile = new File(appBaseDir.getAbsolutePath(),"/upload");
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        System.out.println(targetFile.getAbsolutePath());
    }
}
